//
//  LoginVC.m
//  zhongwulegou
//
//  Created by qianfeng on 15/9/22.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "LoginVC.h"
#import "HttpRequestManager.h"
#import "FMDBManager.h"
#import <CommonCrypto/CommonDigest.h>

@interface LoginVC ()
@property (weak, nonatomic) IBOutlet UITextField *usernameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    [self.view addGestureRecognizer:tap];
    // Do any additional setup after loading the view.
}

-(void)tap
{
    [self.view endEditing:YES];
}

- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)login:(id)sender {
    if (_usernameTF.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号不能为空" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
        [alert show];
    } else if (_passwordTF.text.length == 0){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密码不能为空" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
        [alert show];
    } else{
        [self observeNetStatus];
    }
}

-(void)observeNetStatus
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"通知" message:@"网络错误" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
            [alert show];
        }else{
            [self requestDataFromNet];
        }
    }];
}

//MD5算法加密
-(NSString *)md5:(NSString *)str {
    const char *cStr = [str UTF8String];//转换成utf-8
    unsigned char result[16];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    CC_MD5( cStr, strlen(cStr), result);
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
}

//输出方式用一个for循环来解决更为方便：
//NSMutableString *Mstr = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
//for (int i=0; i<CC_MD5_DIGEST_LENGTH; i++) {
//    [Mstr appendFormat:@"%02X",result[i]];
//}
//return Mstr;




-(void)requestDataFromNet
{
    NSString *passwordMD5 = [self md5:_passwordTF.text];
    
    [[HttpRequestManager shareInstance] loginWithClient:@"ios" andPassword:passwordMD5 andUsername:_passwordTF.text sueecss:^(id responseObj) {
        
        NSLog(@"responseObj==%@",responseObj);
        //解析用户数据
        NSDictionary *dic = responseObj;
        if (dic[@"error"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名或密码错误,请重新输入~" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
            [alert show];
            _passwordTF.text = nil;
        }else{
            NSString *keyStr = dic[@"key"];
            
            //加入数据库
            //1.清除数据库
            FMDBManager *manager = [FMDBManager shareInstance];
            if (![manager.dataBase executeUpdate:@"delete from User"]) {
                NSLog(@"清除表 User 失败");
            }
            //2.插入数据
            if (![manager.dataBase executeUpdate:@"insert into User(client, password , username, key) values('ios',?,?,?)",passwordMD5,_usernameTF.text,keyStr]) {
                NSLog(@"插入用户数据失败");
            }
            
            [self performSegueWithIdentifier:@"showCustomBar" sender:self];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"登录失败,error==%@",error);
    }];
}

- (IBAction)forgetPassword:(id)sender {
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
